package com.icesoft.base.manager.dao.impl;

import com.icesoft.base.manager.dao.IDataScopeFilter;
import com.icesoft.base.manager.entity.security.RelSysRoleOrg;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.entity.manager.RelSysOrgOwner;
import com.icesoft.core.dao.criteria.FromBuilder;
import com.icesoft.core.dao.criteria.PropertyFilter;
import com.icesoft.core.dao.criteria.QueryBuilder;
import com.icesoft.core.dao.criteria.SelectBuilder;

import java.util.List;

public class DataScopeUserFilter implements IDataScopeFilter {

    private PropertyFilter propertyFilter;
    private FromBuilder fromBuilder;
    private int userOrgId;
    private int userOrgPid;
    private int userOrgCompanyId;

    public DataScopeUserFilter(FromBuilder fromBuilder, SysOrg userOrg) {
        this.fromBuilder = fromBuilder;
        this.propertyFilter = fromBuilder.where().andFilter();
        this.userOrgId = userOrg.getId();
        this.userOrgPid = userOrg.getPid();
        this.userOrgCompanyId = userOrg.getCompanyId();
    }


    @Override
    public void scopeCustom(List<Integer> customRoleIds) {
        SelectBuilder orgSelectBuilder = SelectBuilder.select("orgId")
                .builder(QueryBuilder.get(RelSysRoleOrg.class).andIn("roleId", customRoleIds));
        propertyFilter.orIn("orgId", orgSelectBuilder);
    }

    @Override
    public void scopeOrgOwnerCustom() {
        SelectBuilder orgSelectBuilder = SelectBuilder.select("ownerOrgId")
                .builder(QueryBuilder.get(RelSysOrgOwner.class).andEq("orgId", userOrgId));
        propertyFilter.orIn("orgId", orgSelectBuilder);
    }

    @Override
    public void scopeOwnChildOne() {
        SelectBuilder orgSelectBuilder = SelectBuilder.select("id")
                .builder(QueryBuilder.get(SysOrg.class).orEq("pid", userOrgId).orEq("id", userOrgId));
        propertyFilter.orIn("orgId", orgSelectBuilder);
    }

    @Override
    public void scopeOwnLevel() {
        SelectBuilder orgSelectBuilder = SelectBuilder.select("id")
                .builder(QueryBuilder.get(SysOrg.class).andEq("pid", userOrgPid));
        propertyFilter.orIn("orgId", orgSelectBuilder);
    }

    @Override
    public void scopeOwnCompany() {
        fromBuilder.join(SysOrg.class, "o").on("o.id", "orgId");
        propertyFilter.andEq("o.companyId", userOrgCompanyId);
    }

    @Override
    public void scopeOwn() {
        propertyFilter.orEq("orgId", userOrgId);
    }
}
